package com.zj.osm.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import com.bin.david.form.annotation.SmartColumn;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.CleanUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.thoughtworks.xstream.core.util.Base64Encoder;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.bean.DianLjinTable;
import com.zj.osm.bean.HwxTable;
import com.zj.osm.bean.PointNode;
import com.zj.osm.bean.PoleBean;
import com.zj.osm.bean.ProgramTypeTable;
import com.zj.osm.bean.RoadSrcTable;
import com.zj.osm.bean.Trajectory;
import com.zj.osm.entity.db.EquipmentDao;
import com.zj.osm.entity.db.LineDao;
import com.zj.osm.entity.db.PhotosDao;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.db.ProgramTabDao;
import com.zj.osm.entity.db.ProjectDao;
import com.zj.osm.entity.greendao.Equipment;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Photos;
import com.zj.osm.entity.greendao.Point;
import com.zj.osm.entity.greendao.ProgramTab;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.model.pojo.ModuleMaterials;
import com.zj.osm.utils.CoordinateTool;
import com.zj.osm.utils.GaussKrugerProjection;
import com.zj.osm.utils.SQLiteDatabaseUtils;
import com.zj.osm.utils.ZipUtil;
import com.zj.osm.view.project.projectdetail.ProjectDetailActivity;
import com.zj.utils.map.GPSUtils;
import com.zj.utils.map.LocationPoint;
import com.zj.utils.utils.ShareUtils;
import com.zj.utils.utils.ThreadManager;
import com.zj.utils.utils.http.GetToken;
import com.zj.utils.utils.http.HttpConfig;
import com.zj.utils.utils.utilcode.FileUtil;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.jetbrains.annotations.NotNull;
import org.xmlpull.v1.XmlSerializer;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.zj.osm.view.home.home.home_fragment.onefragment.OneFragment.parseXMLWithPulls;
import static com.zj.utils.utils.MathUtils.eval;
import static com.zj.utils.utils.ThreadManager.getThreadPool;
import static com.zj.utils.utils.http.HttpConfig.parseXMLWithPull;

/**
 * 导出文件的工具类
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public
class ExportUnit {
    private ProgressDialog mProgressDialog;
    private Context context;
    private long id;
    private String name;
    Trajectory trajectory;
    //需要耗时的工作
    /**
     * 线程
     */
    private Runnable mRunnable = this::setData;

    /**
     * 线程
     */
    private Runnable mKmlRunnable = () -> {
        //需要耗时的工作
        setKmlData();
    };
    //耗时工作
    private Runnable mTrajectoryRunnble = this::setTrajectoryData;

    private void setTrajectoryData() {
        exportTrajectory();
       /* if (App.getInstances().IsLogin()) {
            if (NetworkUtils.isConnected()) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("surverytaskid", trajectory.getProjectId());
                String result = HttpConfig.callService(1, "getProjectStatusInfo", map);
                if (parseXMLWithPulls(result)) {
                    ToastUtils.showShort("此项目已结束勘测,不可上传");
                } else {
                    if (GetToken.getInstance().getToken()) {
                        exportTrajectory();
                    } else {
                        GetToken.getInstance().setToken();
                        exportTrajectory();
                    }
                }
            } else {
                ToastUtils.showShort("网络连接不可用");
            }
        } else {
            Log.e("stringAniToSting1", trajectory.toString());
            exportTrajectory();
            ToastUtils.showShort("当前未登录");
        }*/
    }

    /**
     * 线程
     */
    private Runnable mAddItemRunnable = () -> {
        //需要耗时的工作
        setAddItemXmlData();
    };


    public ExportUnit(long id, String name) {
        this.context = App.getInstances().getApplicationContext();
        this.id = id;
        this.name = name;
    }

    public ExportUnit(Context context, long id, String name) {
        this.context = context;
        this.id = id;
        this.name = name;
    }

    /**
     * 为XML文件换行
     */
    private static void changeLine(XmlSerializer serializer, String enter) {
        try {
            serializer.text(enter);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }


    /**
     * 生成Zip文件
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void getZipFile() {
        Log.e("name", name.toString());
        ZipUtil.zip(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
        ShareUtils.shareFile(context, file);
    }


    /**
     * 生成Zip文件
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private File getZipsFile() {
        getXmlFile();
        ZipUtil.zip(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
        return new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
    }

    /**
     * 生成Zip文件
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private File getAddItemZipsFile() {
       /* getAddItemXmlFile();
        ZipUtil.zip(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
        return new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
       */
        return getAddItemXmlFile();
    }

    public File getCreateProjectZipsFileKml() {
        //getKmlFile();
        ZipUtil.zip(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
        return new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
    }

    public void getZipsFileKml() {
        ZipUtil.zipCharset(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
        reName(file, "zip", "kmz");
        File filekmz = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".kmz");
        ShareUtils.shareFile(context, filekmz);
    }

    public static void reName(File subFile, String from, String to) {
        String name = subFile.getName();
        if (name.endsWith(from)) {
            subFile.renameTo(new File(subFile.getParent() + "/" + name.substring(0, name.indexOf(from)) + to));
            /*
             * 可在Java API中的File类中查询renameTo的方法
             * renameTo可以用来给File改名字,改路径
             * 他需要的参数也是一个File对象,表示要把当前文件重命名(移动)为哪个文件
             * 如果目标文件存在,则此方法返回false
             *
             * renameTo不会产生新文件,他只是把文件移动一下,或者改个名字
             *
             * 实际上,这个方法的具体表现与操作系统,和文件系统都有关系.
             * 它不能把一个文件从一个文件系统移动到另一个文件系统,例如: 不能把c:\a.txt renameTo 为
             * d:\a.txt 因为c: d:属于不同的盘(文件系统) 但可以把c:\a.txt renameTo
             * c:\system\bb.txt (路径,文件名都可以变,但还是在同一个分区)
             * linux,unix的分区也是同样的道理,只不过不像Windows这么明显一眼就看出来不是同一个分区
             *
             * 你可以在系统中试一下: 在同一个分区内,剪切一个文件 ,在粘贴到另一个位置,这是瞬间完成的,无论文件多么大.
             * 实际上没有copy操作,java的renameTo就是这个意思 不同分区的话,那就得先复制,然后删除源文件
             */
        }
    }

    /**
     * 导出
     */
    public void getKmlFile(List<Point> PointList, List<Line> lines) {
        int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        int permission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    (Activity) context,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        File kmlFile = null;
        Project item = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().unique();
        kmlFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name, name + item.getId() + ".kml");
        Element root = DocumentHelper.createElement("kml");  //根节点是kml
        Document document = DocumentHelper.createDocument(root);
        //给根节点kml添加属性
        root.addAttribute("xmlns", "http://earth.google.com/kml/2.1");
        //给根节点kml添加子节点  Document
        Element documentElement = root.addElement("Document");
        /*Element styleElement = documentElement.addElement("Style"); //添加点的Style
        styleElement.addAttribute("id", "normalState_TLP_Normal");
        Element IconStyleElement = styleElement.addElement("IconStyle");
        Element LabelStyleElement = styleElement.addElement("LabelStyle");
        Element scaleElement = IconStyleElement.addElement("scale");
        Element IconElement = IconStyleElement.addElement("Icon");
        scaleElement.addText("1.0");
        Element hrefElement = IconElement.addElement("href");
        hrefElement.addText("http://10086.gitee.ltd/drawable-xxhdpi/x_bdz.webp");//连接
        Element LabelStyleScaleElement = LabelStyleElement.addElement("scale");
        Element LabelStyleColorElement = LabelStyleElement.addElement("color");
        LabelStyleScaleElement.addText("1.0");
        LabelStyleColorElement.addText("ffffff00");//红绿色
        //按下的Style
        Element styleElementP = documentElement.addElement("Style"); //添加点的Style
        styleElementP.addAttribute("id", "highlightState_TLP_Normal");
        Element IconStyleElementP = styleElementP.addElement("IconStyle");
        Element LabelStyleElementP = styleElementP.addElement("LabelStyle");
        Element scaleElementP = IconStyleElementP.addElement("scale");
        Element IconElementP = IconStyleElementP.addElement("Icon");
        scaleElementP.addText("1.1");
        Element hrefElementP = IconElementP.addElement("href");
        hrefElementP.addText("http://10086.gitee.ltd/drawable-xxhdpi/x_bdz.webp");//连接
        Element LabelStyleScaleElementP = LabelStyleElementP.addElement("scale");
        Element LabelStyleColorElementP = LabelStyleElementP.addElement("color");
        LabelStyleScaleElementP.addText("1.0");
        LabelStyleColorElementP.addText("ff2E83F0");//绿色
        *//*
          <StyleMap id="styleMap_TLP_Start">
            <Pair>
                <key>normal</key>
                <styleUrl>#normalState_TLP_Start</styleUrl>
            </Pair>
            <Pair>
                <key>highlight</key>
                <styleUrl>#highlightState_TLP_Start</styleUrl>
            </Pair>
        </StyleMap>*//*
        Element StyleMapElementP = documentElement.addElement("StyleMap"); //添加点的Style
        StyleMapElementP.addAttribute("id", "styleMap_TLP_Start");
        Element PairElement = StyleMapElementP.addElement("Pair");
        Element PairElement1 = StyleMapElementP.addElement("Pair");

        Element keyElement = PairElement.addElement("key");
        Element styleUrlElement = PairElement.addElement("styleUrl");
        keyElement.addText("normal");
        styleUrlElement.addText("#normalState_TLP_Normal");

        Element keyElement1 = PairElement1.addElement("key");
        Element styleUrlElement1 = PairElement1.addElement("styleUrl");
        keyElement1.addText("highlight");
        styleUrlElement1.addText("#highlightState_TLP_Normal");*/


        //线的Style
        /*<!--线的类型-->
          <Style id="roadStyle">
              <LineStyle>
                  <color>ff00ff00</color>
                  <width>33</width>
              </LineStyle>
          </Style>*/
       /* Element roadStyle = documentElement.addElement("Style");
        roadStyle.addAttribute("id", "roadStyle");
        Element lineStyle = roadStyle.addElement("LineStyle");
        Element roadColor = lineStyle.addElement("color");
        Element roadWidth = lineStyle.addElement("width");
        roadColor.addText("ff00ff00");
        roadWidth.addText("6");*/

        //下面是线的部分。
        Element OpenElement = documentElement.addElement("Open");
        Element descriptionElement = documentElement.addElement("description");
        Element nameElement = documentElement.addElement("name");
        for (int i = 0; i < lines.size(); i++) {
            String lineColor = "ffff0000";
            switch (lines.get(i).getState()) {
                case "新建":
                    lineColor = "ff0000ff";
                    break;
                case "原有":
                    lineColor = "ff000000";
                    break;
                case "改造":
                    lineColor = "ffff0000";
                    break;
                case "拆除":
                    lineColor = "ff828080";
                    break;
            }
            Element roadStyle = documentElement.addElement("Style");
            roadStyle.addAttribute("id", "roadStyle" + i);
            Element lineStyle = roadStyle.addElement("LineStyle");
            Element roadColor = lineStyle.addElement("color");
            Element roadWidth = lineStyle.addElement("width");
            roadColor.addText(lineColor);
            roadWidth.addText("6");

            Element PlacemarkElement = documentElement.addElement("Placemark");
            OpenElement.addText("1");
            descriptionElement.addText("渤海新能科技有限公司");
            nameElement.addText("渤海科技");
            Element palcemarkNameElement = PlacemarkElement.addElement("name");
            Element palcemarkStyleUrlElement = PlacemarkElement.addElement("styleUrl");
            Element palcemarkMultiGeometryElement = PlacemarkElement.addElement("MultiGeometry");
            palcemarkNameElement.addText("Route");
            palcemarkStyleUrlElement.addText("#roadStyle" + i);
            Element lineStyleElement = palcemarkMultiGeometryElement.addElement("LineString");
            Element coordinatesElement = lineStyleElement.addElement("coordinates");
            StringBuilder lineCoord = new StringBuilder();
            lineCoord.append(lines.get(i).getLonA()).append(",").append(lines.get(i).getLatA()).append(",0.00 ").append(lines.get(i).getLonB()).append(",").append(lines.get(i).getLatB()).append(",0.00 ");
            coordinatesElement.addText(lineCoord.toString());
            Log.e("linecoorString==", lineCoord.toString());
        }
        //<!--点的内容-->
        //<Folder>
        //	<name>杆塔设备</name>
        //	<Placemark>
        //		<name>ZXG-01</name>
        //		<styleUrl>#styleMap_TLP_Start</styleUrl>
        //		<Point>
        //			<coordinates>
        //                85.3595886,27.7069111,1331.88
        //                </coordinates>
        //		</Point>
        //	</Placemark>
        //        <Placemark>
        //		<name>ZXG-02</name>
        //		<styleUrl>#styleMap_TLP_Normal</styleUrl>
        //		<Point>
        //			<coordinates>
        //                85.3600540,27.7067261,1332.16
        //                </coordinates>
        //		</Point>
        //       </Placemark>
        //</Folder>
        Element folderElement = documentElement.addElement("Folder");
        //这里for循环就可以
        for (int i = 0; i < PointList.size(); i++) {
            StringBuilder resourceName = new StringBuilder();
            Log.e("shanchu==", PointList.get(i).getState());
            switch (PointList.get(i).getState()) {
                case "原有":
                    resourceName.append("y_");
                    break;
                case "改造":
                    resourceName.append("c_");
                    break;
                case "拆除":
                    resourceName.append("g_");
                    break;
                default:
                    resourceName.append("c_");
                    break;
            }

            if (PointList.get(i).getIcon() == null) {
                resourceName.append("zxg");

            } else {
                if (PointList.get(i).getIsT() == null) {
                    resourceName.append(PointList.get(i).getIcon().toLowerCase());
                } else {
                    if (PointList.get(i).getIsT().equals("1") || PointList.get(i).getIsT().equals("2")) {
                        resourceName.append("f");
                    } else {
                        resourceName.append(PointList.get(i).getIcon().toLowerCase());
                    }

                }
            }

            Element styleElement = documentElement.addElement("Style"); //添加点的Style
            styleElement.addAttribute("id", "normalState_TLP_Normal" + i);
            Element IconStyleElement = styleElement.addElement("IconStyle");
            Element LabelStyleElement = styleElement.addElement("LabelStyle");
            Element scaleElement = IconStyleElement.addElement("scale");
            Element IconElement = IconStyleElement.addElement("Icon");
            scaleElement.addText("1.0");
            Element hrefElement = IconElement.addElement("href");
            hrefElement.addText("http://10086.gitee.ltd/drawable-xxhdpi/" + resourceName.toString() + ".webp");//连接
            Log.e("iconurl=", "http://10086.gitee.ltd/drawable-xxhdpi/" + resourceName.toString() + ".webp");
            Element LabelStyleScaleElement = LabelStyleElement.addElement("scale");
            Element LabelStyleColorElement = LabelStyleElement.addElement("color");
            LabelStyleScaleElement.addText("1.0");
            LabelStyleColorElement.addText("ffffff00");//红绿色
            //按下的Style
            Element styleElementP = documentElement.addElement("Style"); //添加点的Style
            styleElementP.addAttribute("id", "highlightState_TLP_Normal" + i);
            Element IconStyleElementP = styleElementP.addElement("IconStyle");
            Element LabelStyleElementP = styleElementP.addElement("LabelStyle");
            Element scaleElementP = IconStyleElementP.addElement("scale");
            Element IconElementP = IconStyleElementP.addElement("Icon");
            scaleElementP.addText("1.1");
            Element hrefElementP = IconElementP.addElement("href");
            hrefElementP.addText("http://10086.gitee.ltd/drawable-xxhdpi/" + resourceName.toString() + ".webp");//连接
            Element LabelStyleScaleElementP = LabelStyleElementP.addElement("scale");
            Element LabelStyleColorElementP = LabelStyleElementP.addElement("color");
            LabelStyleScaleElementP.addText("1.0");
            LabelStyleColorElementP.addText("ff2E83F0");//绿色

            Element StyleMapElementP = documentElement.addElement("StyleMap"); //添加点的Style
            StyleMapElementP.addAttribute("id", "styleMap_TLP_Start" + i);
            Element PairElement = StyleMapElementP.addElement("Pair");
            Element PairElement1 = StyleMapElementP.addElement("Pair");

            Element keyElement = PairElement.addElement("key");
            Element styleUrlElement = PairElement.addElement("styleUrl");
            keyElement.addText("normal");
            styleUrlElement.addText("#normalState_TLP_Normal" + i);

            Element keyElement1 = PairElement1.addElement("key");
            Element styleUrlElement1 = PairElement1.addElement("styleUrl");
            keyElement1.addText("highlight");
            styleUrlElement1.addText("#highlightState_TLP_Normal" + i);
            Element folderOfName = folderElement.addElement("name");
            folderOfName.addText("杆塔设备");


            Element folderOfPlacemark = folderElement.addElement("Placemark");
            Element folderOfPlacemarkName = folderOfPlacemark.addElement("name");
            Element folderOfPlacemarkStyleUrl = folderOfPlacemark.addElement("styleUrl");
            Element folderOfPlacemarkPoint = folderOfPlacemark.addElement("Point");
            folderOfPlacemarkName.addText(PointList.get(i).getMark());
            folderOfPlacemarkStyleUrl.addText("#styleMap_TLP_Start" + i);
            Element folderOfPlacemarkPointcoord = folderOfPlacemarkPoint.addElement("coordinates");
            String pointCoord = PointList.get(i).getLongitude() + "," + PointList.get(i).getLatitude() + ",0.00";
            Log.e("pointCoord==", pointCoord);
            //117.09919572157128,39.08656052262791,0.00 117.09954111788956,39.086419549704374,0.00 117.09976521423965,39.08682821156796,0.00 117.0992367902445,39.08694616848226,0.00 117.0995388088601,39.08726821225849,0.00 117.10020857253402,39.087305752058306,0.00 117.09923110904663,39.08774366189197,0.00 117.09986749910267,39.087644677006566,0.00 117.09954563933289,39.08803941999208,0.00 117.10029126563424,39.087733556034586,0.00 117.10032063712985,39.08831516670068,0.00 117.09923257466716,39.088098130304864,0.00

            folderOfPlacemarkPointcoord.addText(pointCoord);
        }


        //将kml写出本地
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");//设置编码格式
        XMLWriter xmlWriter = null;
        try {
            xmlWriter = new XMLWriter(new FileOutputStream(kmlFile.getAbsolutePath()), format);
            xmlWriter.write(document);
            xmlWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传服务器数据
     */
    public void SetExport() {
        ThreadManager.ThreadPool threadPool = getThreadPool();
        threadPool.execute(mRunnable);
    }

    /**
     * 上传服务器kml
     */
    public void setKmlExport() {
        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setMessage("上传数据中,请稍等...");
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
        //启动线程
        ThreadManager.ThreadPool threadPool = getThreadPool();
        threadPool.execute(mKmlRunnable);
    }

    /**
     * 上传服务器kml
     */
    public void setAddItemExport() {
        //启动线程
        ThreadManager.ThreadPool threadPool = getThreadPool();
        threadPool.execute(mAddItemRunnable);
    }

    public void sendServerTrajectory(Trajectory trajectory) {
        this.trajectory = trajectory;
        ThreadManager.ThreadPool threadPool = getThreadPool();
        threadPool.execute(mTrajectoryRunnble);
        //上传1就行
    }

    /**
     * 设置数据
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void setData() {
        try {
            if (NetworkUtils.isConnected()) {
                export();
            } else {
                ToastUtils.showShort("网络连接不可用");
            }
        } catch (Exception e) {
            Log.e("eeerolll=", e.getMessage());
        }
    }

    //项目新增
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void setAddItemXmlData() {
        if (NetworkUtils.isConnected()) {
            exportAddItemKml();
        }
        /*List<Project> ProjectList = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().list();
        Project Project = ProjectList.get(0);
        if (App.getInstances().IsLogin()) {
            if (NetworkUtils.isConnected()) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("surverytaskid", Project.getProjectId());
                String result = HttpConfig.callService(1, "getProjectStatusInfo", map);
                System.out.println("addProjecttatusInfo=" + result);
                if (parseXMLWithPulls(result)) {
                    ToastUtils.showShort("此项目已结束勘测,不可上传");
                } else {
                    if (GetToken.getInstance().getToken()) {
                        exportAddItemKml();
                    } else {
                        GetToken.getInstance().setToken();
                        exportAddItemKml();
                    }
                }
            } else {
                ToastUtils.showShort("网络连接不可用");
            }
        } else {
            //导出项目测试
            exportAddItemKml();
            ToastUtils.showShort("当前未登录");
        }*/
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void setKmlData() {
        List<Project> ProjectList = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().list();
        Project Project = ProjectList.get(0);
        if (App.getInstances().IsLogin()) {
            if (NetworkUtils.isConnected()) {
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("surverytaskid", Project.getProjectId());
                String result = HttpConfig.callService(1, "getProjectStatusInfo", map);
                if (parseXMLWithPulls(result)) {
                    ToastUtils.showShort("此项目已结束勘测,不可上传");
                } else {
                    if (GetToken.getInstance().getToken()) {
                        exportKml();
                    } else {
                        GetToken.getInstance().setToken();
                        exportKml();
                    }
                }
            } else {
                ToastUtils.showShort("网络连接不可用");
            }
        } else {
            ToastUtils.showShort("当前未登录");
        }
    }

    /**
     * 上传轨迹xml
     */
    private void exportTrajectory() {
        File fileKml = getTrajectoryXmlFile(trajectory);
        try {
            LinkedHashMap map = new LinkedHashMap();//TODO 必须用这个有序的 webservers访问需要。有序因为是方法的参数有序的。不然就会调用对应不到。调试遇到的。
            Project Project = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().list().get(0);
            //TODO 开始-------上传附件
            FileInputStream upfileIn = new FileInputStream(fileKml);
            byte[] upbytes = new byte[upfileIn.available()];
            upfileIn.read(upbytes);
            upfileIn.close();
            Base64Encoder encoder = new Base64Encoder();
            String base64str = encoder.encode(upbytes);
            map.put("trajectory", base64str);
            String result = HttpConfig.callService(1, "setTrajectory", map);
            parseXMLWithPull(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向服务器上传zip包
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void export() {
        //TODO 图片来个：如果是xml那么文件名称需要英文要么用时间搓代替。不然乱码后台。调试遇到的问题。
        File files = getZipsFile();
        try {
            LinkedHashMap map = new LinkedHashMap();//TODO 必须用这个有序的 webservers访问需要。有序因为是方法的参数有序的。不然就会调用对应不到。调试遇到的。
            Project Project = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().list().get(0);
            //TODO 开始-------上传附件
            FileInputStream upfileIn = new FileInputStream(files);
            byte[] upbytes = new byte[upfileIn.available()];
            upfileIn.read(upbytes);
            upfileIn.close();
            Base64Encoder encoder = new Base64Encoder();
            String base64str = encoder.encode(upbytes);
            map.put("data", base64str);
            map.put("surverytaskid", Project.getProjectId());
            String result = HttpConfig.callService(1, "setSurveyTasksBaseInfo", map);
            Log.e("@@@@@resulltllllll", result);
            if (!result.equals("字节数组参数不能为空")) {
                Log.e("@@@@@@@@", "导出？");
                if (parseXMLWithPull(result)) {
                    ToastUtils.showShort("导出到服务端成功");
                } else {
                    ToastUtils.showShort("上传失败");
                }
            }

        } catch (IOException e) {
            Log.e("erro", e.getMessage());
            e.printStackTrace();
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void exportKml() {
        File fileKml = getAddItemXmlFile();// getCreateProjectZipsFileKml();
        try {
            LinkedHashMap map = new LinkedHashMap();//TODO 必须用这个有序的 webservers访问需要。有序因为是方法的参数有序的。不然就会调用对应不到。调试遇到的。
            Project Project = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().list().get(0);
            //TODO 开始-------上传附件
            FileInputStream upfileIn = new FileInputStream(fileKml);
            byte[] upbytes = new byte[upfileIn.available()];
            upfileIn.read(upbytes);
            upfileIn.close();
            //byte[] buffer = bos.toByteArray();
            Base64Encoder encoder = new Base64Encoder();
            String base64str = encoder.encode(upbytes);
            map.put("data", base64str);
            map.put("surverytaskid", Project.getProjectId());
            String result = HttpConfig.callService(1, "setSurveyTasksBaseInfo", map);
            if (parseXMLWithPull(result)) {
                ToastUtils.showShort("上传成功");
                mProgressDialog.dismiss();
            } else {
                ToastUtils.showShort("上传失败");
                mProgressDialog.dismiss();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //项目新增
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void exportAddItemKml() {
        File fileKml = getAddItemZipsFile();
        try {
            LinkedHashMap map = new LinkedHashMap();//TODO 必须用这个有序的 webservers访问需要。有序因为是方法的参数有序的。不然就会调用对应不到。调试遇到的。
            //TODO 开始-------上传附件
            FileInputStream upfileIn = new FileInputStream(fileKml);
            byte[] upbytes = new byte[upfileIn.available()];
            upfileIn.read(upbytes);
            upfileIn.close();
            Base64Encoder encoder = new Base64Encoder();
            String base64str = encoder.encode(upbytes);
            map.put("projectInfo", base64str);
            map.put("userId", SPUtils.getInstance().getString("userId"));
            Log.e("addProject=userId", SPUtils.getInstance().getString("userId"));
            String result = HttpConfig.callService(1, "setProjectInfo", map);
            if (parseXMLWithPull(result)) {
                ToastUtils.showShort("上传成功");
            } else {
                ToastUtils.showShort("上传失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 本地导出
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void SetLocalExport() {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_add_concealed_dialog, null);
        Button alertSureTv = view.findViewById(R.id.add_sure);
        Button alertCancelTv = view.findViewById(R.id.add_cancle);
        CheckBox alertCheckBox = view.findViewById(R.id.add_cb);
        alertCheckBox.setChecked(true);
        //显示确认框
        AlertDialog mAlertDialog = new AlertDialog.Builder(context).setView(view).create();
        mAlertDialog.show();

        //取消
        alertSureTv.setOnClickListener(view1 -> mAlertDialog.cancel());
        //导出
        alertCancelTv.setOnClickListener(view12 -> {
            getXmlFile();
            //refreshMediaStore();
            if (alertCheckBox.isChecked()) {
                getZipFile();
            } else {
                //************2019年7月3日修改的内容:让其导出的内容都是zip格式************/
                ZipUtil.zip(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + "/" + name, Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
                //***********2019年7月3日结束*****************/
                File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/" + name + ".zip");
                ShareUtils.shareFile(context, files);
            }
            mAlertDialog.cancel();
        });

    }

    /**
     * 通过点id查询equip_modleType里面的
     *
     * @param id id
     * @return 子类集合
     */
    private String getEquipId(String id, String need) {
        String result = "";
        if (!id.isEmpty() && !need.isEmpty()) {
            SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
            assert db != null;
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from ModuleProperty where ModuleID=" + "'" + id + "'", null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                if (cursor.getString(2).equals(need)) {
                    result = cursor.getString(3);
                    break;
                }
            }
            cursor.close();

        }
        return result;
    }

    /**
     * 通过点点id查询equip_modleType里面的
     *
     * @return 子类集合
     */
    private String getModleCode(String modleId) {
        String result = "";
        if (!modleId.isEmpty()) {
            SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
            assert db != null;
            @SuppressLint("Recycle") Cursor cursor = db.rawQuery("select * from Module where ModuleID=" + "'" + modleId + "'", null);//此处的db是表名，name是列名
            while (cursor.moveToNext()) {
                if (cursor.getString(3) != null) {
                    result = cursor.getString(3);
                }
            }
            cursor.close();

        }
        return result;
    }

    /**
     * 1.生成excle表格
     * 所有电缆井
     */

    public void generateExcle() {
        Project project = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).list().get(0);
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/";
        File files = new File(filePath);
        if (!files.exists()) {
            files.mkdirs();
        }
        String excelName = project.getName();
        //生成三表合一的excle表格
        //1-1 现状廊道资源台账
        List<RoadSrcTable> srcTables = getSrcTablesList(project);
        //1-2 现状电缆井台账
        List<DianLjinTable> srcTables_2 = getSrc2TablesList(project);
        //1-3 现状环网箱台账
        List<HwxTable> srcTables_3 = getSrc3TablesList(project);
        String[] srcTitle = {"序号", "所属网格", "道路名称", "道路主次路", "敷设方式", "通道起段", "通道讫段", "电缆沟规格","电缆支架规格（架长*间距*高度）", "电缆排管规格", "已占用", "剩余通道数", "通道利用率（%）", "通道内线路分布情况"};
//        String[] srcTitle_2 = {"序号", "道路名称", "网格名称", "电缆井编号", "电缆井性质","电缆井尺寸(米）", "纬度", "经度", "X", "Y", "Z", "电缆井观察描述", "道路位置", "电缆井地址", "资源状态", "规划年"};
        String[] srcTitle_2 = {"序号", "道路名称", "网格名称", "电缆井编号", "电缆井性质","电缆井尺寸(米）", "纬度", "经度", "X", "Y", "Z", "电缆井观察描述"};
        String[] srcTitle_3 = {"序号", "道路名称", "网格名称", "道路性质", "环网箱编号", "环网箱类型", "规格", "剩余间隔数", "纬度", "经度", "X", "Y", "Z", "无铭牌", "铭牌错误", "无间隔电缆走向牌", "道路位置", "备注"};

        String excelFileName = "/" + "现状廊道资源台账" + ".xls";
        String resultPath = files.getAbsolutePath()+File.separator+excelName+ excelFileName;
        ExcelUtil.initExcelPole3("", resultPath, srcTitle, srcTitle_2, srcTitle_3);
        ExcelUtil.write3ObjListToExcelToProgram(srcTables, srcTables_2, srcTables_3, resultPath, context);
        //ShareUtils.shareFile(context, moudleFile);


        //生成单独的电缆井excle表格
        List<ProgramTypeTable> programList = getProgramList(project);
        String[] title = {"序号", "所属网格",
                "电缆井编号", "沟内无支架",
                "电缆线路没有固定在支架上",
                "弱电线路占用排管数", "强弱电共沟",
                "强弱电共用一个管", "共用廊道",
                "电缆有泡水", "剩余通道位于最底部",
                "沟内有塌方", "电缆盖板损坏",
                "电缆盖板不规范", "排管有损坏",
                "沟内有积水、淤泥",
                "是否有电缆分接头", "与其他市政管线共沟共井"
        };
        String excelFileName1 = "/" + "廊道现状问题清册" + ".xls";
        String resultPath1 = files.getAbsolutePath()+File.separator+excelName + excelFileName1;
        ExcelUtil.initExcelPole("", resultPath1, title);
        File moudleFile1 = ExcelUtil.writeObjListToExcelToProgram(programList, resultPath1, context);
        //ShareUtils.shareFile(context, moudleFile1);
        //创建项目文件夹
        String programSrc = filePath + excelName;
        boolean createDir = FileUtils.createOrExistsDir(programSrc);
        if (!createDir) {
            //如果有目录存在那么先删除再次创建即可
            FileUtils.deleteAllInDir(programSrc);
            //再次创建目录
            FileUtils.createOrExistsDir(programSrc);
        }
        //打包zip然后分享
        ZipUtil.zip(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name, programSrc+ ".zip");
        //***********2019年7月3日结束*****************/
        File zipfile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + ".zip");
        ShareUtils.shareFile(context, zipfile);
    }

    private List<HwxTable> getSrc3TablesList(Project project) {
        List<HwxTable> dianLjinTables = new ArrayList<>();
        List<Point> allPoints = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(project.getId()), PointDao.Properties.EquipType_name.eq("环网箱")).list();
        for (int index = 0; index < allPoints.size(); index++) {
            Point point = allPoints.get(index);
            HwxTable programTypeTable = new HwxTable();
            programTypeTable.setID(String.valueOf(index + 1));
            programTypeTable.setRoadName(removeNull(point.getRoadName()));
            programTypeTable.setOwnGridName(removeNull(point.getGridName()));
            programTypeTable.setRoadZName(removeNull(point.getRoadNature()));
            programTypeTable.setHwxNumber(removeNull(point.getMark()));
            programTypeTable.setHwxType(removeNull(point.getCabwellPy()));
            programTypeTable.setHwxNature(removeNull(point.getReSpecfs()));
            programTypeTable.setJgNumber("0");
            double[] latAndLon = GPSUtils.wgs2BD09(point.getLatitude(), point.getLongitude());
            programTypeTable.setLatitude(removeNull(String.valueOf(latAndLon[0])));
            programTypeTable.setLongitude(removeNull(String.valueOf(latAndLon[1])));
            programTypeTable.setX("");
            programTypeTable.setY("");
            programTypeTable.setZ("");
            programTypeTable.setRoadLocation(removeNull(point.getRoadAdress()));
            programTypeTable.setNote(removeNull(point.getNote()));
            String problem1 = getProgramNumber(allPoints.get(index).getId(), "无铭牌");
            programTypeTable.setNoPlaque(removeNull(problem1));
            String problem2 = getProgramNumber(allPoints.get(index).getId(), "铭牌错误");
            programTypeTable.setPlaqueErro(removeNull(problem2));
            String problem3 = getProgramNumber(allPoints.get(index).getId(), "无间隔电缆走向牌");
            programTypeTable.setWjjDlPlaque(removeNull(problem3));
            dianLjinTables.add(programTypeTable);
        }
        return dianLjinTables;
    }

    private List<DianLjinTable> getSrc2TablesList(Project project) {
        List<DianLjinTable> dianLjinTables = new ArrayList<>();
        List<Point> allPoints = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(project.getId()), PointDao.Properties.EquipType_name.eq("电缆井")).list();
        for (int index = 0; index < allPoints.size(); index++) {
            Point point = allPoints.get(index);
            DianLjinTable programTypeTable = new DianLjinTable();
            programTypeTable.setID(String.valueOf(index + 1));
            programTypeTable.setRoadName(removeNull(point.getRoadName()));
            programTypeTable.setOwnGridName(removeNull(point.getGridName()));
            programTypeTable.setDljNumber(removeNull(point.getMark()));
            programTypeTable.setDljProperty(removeNull(point.getCabwellPy()));
            programTypeTable.setDljcc(removeNull(point.getDljCC()));//dljcc
            double[] latAndLon = GPSUtils.wgs2BD09(point.getLatitude(), point.getLongitude());
            programTypeTable.setLatitude(removeNull(String.valueOf(latAndLon[0])));
            programTypeTable.setLongitude(removeNull(String.valueOf(latAndLon[1])));
            programTypeTable.setX("");
            programTypeTable.setY("");
            programTypeTable.setZ("");
            programTypeTable.setNote(removeNull(point.getNote()));
//            programTypeTable.setRoadLocation(removeNull(point.getRoadAdress()));
//            programTypeTable.setDljAddress(removeNull(point.getAddress()));
//            programTypeTable.setResourceStatus(removeNull(point.getRsState()));
//            programTypeTable.setPlanYear(removeNull(point.getGhYear()));

            dianLjinTables.add(programTypeTable);

        }
        return dianLjinTables;
    }

    private List<RoadSrcTable> getSrcTablesList(Project project) {
        List<RoadSrcTable> roadSrcTables = new ArrayList<>();
        List<Line> allLines = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(project.getId())).list();
        //这里来获取数据给table数据整理。
        for (int index = 0; index < allLines.size(); index++) {
            Line line = allLines.get(index);
            RoadSrcTable programTypeTable = new RoadSrcTable();
            programTypeTable.setID(String.valueOf(index + 1));
            programTypeTable.setOwnGrid(removeNull(line.getModuleTxt()));
            programTypeTable.setRoadName(removeNull(line.getName()));
            programTypeTable.setRoadZName(removeNull(line.getRoadPands()));
            //辐射方式
            programTypeTable.setLayingMethod(removeNull(line.getResType()));
            //通道起段
            //programTypeTable.setRoadStarName(removeNull(line.getResType()));
            List<Point> listPoinsStar = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(line.getStart_id())).list();
            if (!listPoinsStar.isEmpty()) {
                programTypeTable.setRoadStarName(listPoinsStar.get(0).getMark());
            }

            List<Point> listPoinsEnd = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.Uid.eq(line.getEnd_id())).list();
            if (!listPoinsEnd.isEmpty()) {
                programTypeTable.setRoadEndName(listPoinsEnd.get(0).getMark());
            }
            //电缆沟规格
            programTypeTable.setDlgGz(removeNull(line.getResSpec()));
            //电缆配管规格
            programTypeTable.setDlpgGG(removeNull(line.getResSpec()));
            //已经占用
            programTypeTable.setAlreadyOccupy(removeNull(line.getArdUseNumer()));
            //电缆支架规格（架长*间距*高度）
            programTypeTable.setTdGG(removeNull(removeNull(line.getDlzjSpec())));
            //剩余数量
            programTypeTable.setRoadNumber(removeNull(line.getRemaNumber()));
            //通道利用率
            programTypeTable.setRoadRatio(removeNull(line.getRoadUtili()));
            programTypeTable.setRoadLinePush(removeNull(line.getNote()));
            roadSrcTables.add(programTypeTable);
        }
        return roadSrcTables;
    }

    private String removeNull(String resSpec) {
        if (null == resSpec) {
            resSpec = "";
        }
        return resSpec;
    }

    @NotNull
    private List<ProgramTypeTable> getProgramList(Project project) {
        List<ProgramTypeTable> programTypeTables = new ArrayList<>();
        List<Point> allPoins = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(project.getId()), PointDao.Properties.EquipType_name.eq("电缆井")).list();
        //这里来获取数据给table数据整理。
        for (int index = 0; index < allPoins.size(); index++) {
            Point point = allPoins.get(index);
            ProgramTypeTable programTypeTable = new ProgramTypeTable();
            programTypeTable.setID(String.valueOf(index + 1));
            programTypeTable.setOwnGrid(allPoins.get(index).getGridName());
            programTypeTable.setCableWellNumber(point.getMark() + "");
            //TODO 这里去查询问题
            String problem1 = getProgramNumber(allPoins.get(index).getId(), "沟内无支架");
            programTypeTable.setProgram1(problem1);

            String problem2 = getProgramNumber(allPoins.get(index).getId(), "电缆线路没有固定在支架上");
            programTypeTable.setProgram2(problem2);

            String problem3 = getProgramNumber(allPoins.get(index).getId(), "弱电线路占用排管数");
            programTypeTable.setProgram3(problem3);

            String problem4 = getProgramNumber(allPoins.get(index).getId(), "强弱电共沟");
            programTypeTable.setProgram4(problem4);

            String problem5 = getProgramNumber(allPoins.get(index).getId(), "强弱电共用一个管");
            programTypeTable.setProgram5(problem5);

            String problem6 = getProgramNumber(allPoins.get(index).getId(), "共用廊道");
            programTypeTable.setProgram6(problem6);

            String problem7 = getProgramNumber(allPoins.get(index).getId(), "电缆有泡水");
            programTypeTable.setProgram7(problem7);

            String problem8 = getProgramNumber(allPoins.get(index).getId(), "剩余通道位于最底部");
            programTypeTable.setProgram8(problem8);

            String problem9 = getProgramNumber(allPoins.get(index).getId(), "沟内有塌方");
            programTypeTable.setProgram9(problem9);

            String problem10 = getProgramNumber(allPoins.get(index).getId(), "电缆盖板损坏");
            programTypeTable.setProgram10(problem10);

            String problem11 = getProgramNumber(allPoins.get(index).getId(), "电缆盖板不规范");
            programTypeTable.setProgram11(problem11);

            String problem12 = getProgramNumber(allPoins.get(index).getId(), "排管有损坏");
            programTypeTable.setProgram12(problem12);

            String problem13 = getProgramNumber(allPoins.get(index).getId(), "沟内有积水、淤泥");
            programTypeTable.setProgram13(problem13);

            String problem14 = getProgramNumber(allPoins.get(index).getId(), "是否有电缆分接头");
            programTypeTable.setProgram14(problem14);

            String problem15 = getProgramNumber(allPoins.get(index).getId(), "与其他市政管线共沟共井");
            programTypeTable.setProgram15(problem15);

            programTypeTables.add(programTypeTable);

        }
        return programTypeTables;
    }

    private String getProgramNumber(Long PointID, String prName) {
        List<ProgramTab> programProblem1 = App.getInstances().getDaoSession().getProgramTabDao().queryBuilder().where(ProgramTabDao.Properties.PointID.eq(PointID), ProgramTabDao.Properties.PrName.eq(prName)).list();
        if (programProblem1.isEmpty()) {
            return "";
        } else {
            return "1";
        }
    }

    /**
     * 生成XML文件
     */
    public File getXmlFile() {
        int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        int permission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    (Activity) context,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        File xmlFile = null;
        Project item = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().unique();
        List<Point> czzt = new ArrayList<>();
        List<Point> czztOne = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(id), PointDao.Properties.Whether.isNull()).build().list();
        List<Point> otherPoint = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(id), PointDao.Properties.Whether.eq("0")).build().list();
        czzt.addAll(czztOne);
        czzt.addAll(otherPoint);
        //Log.e("czzt.size",czzt.size()+"");
        /*for (int i = 0; i < czztOut.size(); i++) {//排除地形点里面的连接点和电缆拐点。
            if (!czztOut.get(i).getName().contains("连接点") && !czztOut.get(i).getName().contains("电缆拐点")) {
                czzt.add(czztOut.get(i));
            }
        }*/
        //地形点 里面如果是拐点和连接点那就不管。其他的地形点是4
        List<Point> czzts = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(id), PointDao.Properties.Whether.eq("4")).build().list();
        String enter = System.getProperty("line.separator");//换行
        //这里是保存文件夹。
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name + "/" + name);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
       /* File fileflag = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name);
        if (fileflag.exists()){
            //1。这里处理图片了。将文件中的图片进行复制到bhne/img下面。
            File fileImag = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + "img");
            if (!fileImag.exists() && !fileImag.isDirectory()) {
                fileImag.mkdirs();
            }
            for (int i = 0; i <fileflag.listFiles().length; i++) {
                if(fileflag.listFiles()[i].getAbsolutePath().endsWith(".jpg")||fileflag.listFiles()[i].getAbsolutePath().endsWith(".png")||fileflag.listFiles()[i].getAbsolutePath().endsWith(".jpeg")){
                    copyFile(fileflag.listFiles()[i].getAbsolutePath(),fileImag.getAbsolutePath()+"/"+fileflag.listFiles()[i].getName());
                }
            }
            //2。清楚项目目录如果存在
            //CleanUtils.cleanCustomDir(fileflag);
        }

        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        //3.写入到目录就行了。
        File fileImag = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + "img");
        for (int i = 0; i <fileImag.listFiles().length; i++) {
            if(fileImag.listFiles()[i].getAbsolutePath().endsWith(".jpg")||fileImag.listFiles()[i].getAbsolutePath().endsWith(".png")||fileImag.listFiles()[i].getAbsolutePath().endsWith(".jpeg")){
                copyFile(fileImag.listFiles()[i].getAbsolutePath(),file.getAbsolutePath()+"/"+fileflag.listFiles()[i].getName());
            }
        }
*/


        try {
            if (czzt.size() > 0 || czzts.size() > 0) {
                File xmlsFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + "/" + name);
                if (xmlsFile.isDirectory()) {
                    String[] allFile = xmlsFile.list();
                    for (int i = 0; i < allFile.length; i++) {
                        Log.e("string[ii]=", allFile[i]);
                        FileUtils.deleteFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/bhne/" + name + "/" + name + "/" + allFile[i]);
                    }
                }
                xmlFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/bhne/" + name + "/" + name, name + item.getId() + ".xml");
                xmlFile.setWritable(true);
                FileOutputStream fileos = new FileOutputStream(xmlFile);
                XmlSerializer serializer = Xml.newSerializer();
                serializer.setOutput(fileos, "UTF-8");
                serializer.startDocument(null, true);
                changeLine(serializer, enter);
                serializer.startTag(null, "Projects");
                changeLine(serializer, enter);
                serializer.startTag(null, "ProjectId");
                serializer.text(item.getProjectId() + "");
                serializer.endTag(null, "ProjectId");
                changeLine(serializer, enter);
                serializer.startTag(null, "Voltage");
                serializer.text(item.getVoltage() + "");
                serializer.endTag(null, "Voltage");
                //状态
                serializer.startTag(null, "State");
                serializer.text(item.getType() + "");
                serializer.endTag(null, "State");
                //版本号
                serializer.startTag(null, "AppVersion");
                serializer.text("App版本号:" + AppUtils.getAppVersionName());
                serializer.endTag(null, "AppVersion");
                //项目备注
                serializer.startTag(null, "Note");
                serializer.text(item.getNote() + "");
                serializer.endTag(null, "Note");
                changeLine(serializer, enter);
                for (Point Point : czzt) {
                    System.getProperty("line.separator");//换行
                    serializer.startTag(null, "Point");
                    serializer.attribute(null, "Dangjv", Point.getDangju() + "");
                    serializer.attribute(null, "Weidu", Point.getLatitude() + "");
                    serializer.attribute(null, "Jindu", Point.getLongitude() + "");
                    //百度经纬度转为墨卡托x,y
                    GaussKrugerProjection.Tuple tuple = get2000XY(Point.getLatitude().toString(), Point.getLongitude().toString());
                    serializer.attribute(null, "X", tuple.getB() + "");
                    serializer.attribute(null, "Y", tuple.getL() + "");
                    serializer.attribute(null, "Glsb", Point.getGlsb() + "");
                    serializer.attribute(null, "Sbzt", (Point.getState() == null || Point.getState().equals("null")) ? "新建" : Point.getState());
                    if (Point.getLegendTypeKey() != null) {
                        serializer.attribute(null, "LegendTypeKey", Point.getLegendTypeKey().trim().replace("&#13;", "").replace("\n", "") + "");
                    }
                    //    //关联设备的 DefaultLineType;
                    if (Point.getDefaultLineType() != null) {
                        serializer.attribute(null, "DefaultLineType", Point.getDefaultLineType() + "");
                    } else {
                        serializer.attribute(null, "DefaultLineType", getDefaultLineType(Point.getSblx()) + "");
                    }
                    //模块选型Id
                    serializer.attribute(null, "ModuleId", Point.getMark() + "");
                    serializer.attribute(null, "Sbbh", Point.getMark() + "");
                    serializer.attribute(null, "High", Point.getHigh() + "");
                    serializer.attribute(null, "Sblb", Point.getName() + "");
                    serializer.attribute(null, "Sblx", Point.getSblx() + "");
                    serializer.attribute(null, "Ms", Point.getNote() + "");
                    serializer.attribute(null, "flag", Point.getMark() + "");
                    serializer.attribute(null, "ID", Point.getId() + "");
                    serializer.attribute(null, "UID", Point.getUid() + "");
                    serializer.attribute(null, "CID", Point.getUid() + "");
                    serializer.attribute(null, "Note", Point.getNote() + "");
                    serializer.attribute(null, "Whether", Point.getWhether() + "");
                    serializer.attribute(null, "isT", Point.getIsT() == null ? "0" : Point.getIsT());
                    serializer.attribute(null, "Icon", getIconBySblx(Point.getSblx(), context) + "");
                    serializer.attribute(null, "Address", Point.getAddress() + "");
                    if (Point.getSblx().equals("柱上变压器")) {
                        serializer.attribute(null, "Zhugan", Point.getLonA() + "");
                        serializer.attribute(null, "Fugan", Point.getLonB() + "");
                    }

                    //serializer.attribute(null, "Index", Point.getId() + "");
                    changeLine(serializer, enter);
                    List<Equipment> equipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(Point.getId())).whereOr(EquipmentDao.Properties.Qubie.eq(2), EquipmentDao.Properties.Qubie.eq(5), EquipmentDao.Properties.Qubie.eq(8), EquipmentDao.Properties.Qubie.eq(9), EquipmentDao.Properties.Qubie.eq(2), EquipmentDao.Properties.Qubie.eq(10), EquipmentDao.Properties.Qubie.eq(11)).build().list();
                    changeLine(serializer, enter);
                    for (Equipment equipment : equipmentList) {
                        serializer.startTag(null, "ColumnModel");
                        serializer.attribute(null, "Amount", equipment.getAmount() + "");
                        serializer.attribute(null, "Module_ID", equipment.getThreeId() + "");
                        serializer.attribute(null, "Module_Name", equipment.getThreeName() + "");
                        serializer.attribute(null, "ModuleXH_ID", equipment.getThreeId() + "");
                        serializer.attribute(null, "ModuleXH_Name", equipment.getThreeName() + "");
                        serializer.attribute(null, "ModuleZL_ID", equipment.getHead_id() + "");
                        serializer.attribute(null, "ModuleZL_Name", equipment.getTwoName() + "");
                        serializer.attribute(null, "ModuleFL_ID", equipment.getLever_id() + "");
                        serializer.attribute(null, "ModuleFL_Name", equipment.getName() + "");
                        serializer.attribute(null, "Module_Code", getModleCode(equipment.getThreeId() + "") + "");
                        serializer.attribute(null, "PID", equipment.getId() + "");
                        //serializer.attribute(null, "Index", equipment.getId() + "");
                        //物料开始节点
                        serializer.startTag(null, "PointMaterials");
                        //获取点的物料信息
                        if (equipment.getThreeId() != null) {
                            List<ModuleMaterials> moduleMaterials = getModuleMaterials(equipment.getThreeId(), null);
                            if (moduleMaterials != null && moduleMaterials.size() > 0) {
                                Log.e("TAG", "getXmlFile点: " + moduleMaterials.toString());
                                //[MoudleMaterials{MaterialsProjectID='825', MaterialCodeERP='500112260', MaterialName='柱上断路器', Spec='AC10kV,630A,20kA,真空,无隔离闸刀,用户分界，空气绝缘,电动,弹簧,共箱式,普通', ERPUnit='台', num='1', TechnicalProtocol='9906-500112264-00003', Voltage='10kV'}]
                                //[MoudleMaterials{MaterialsProjectID='827', MaterialCodeERP='500002150', MaterialName='10kV三相隔离开关', Spec='630A,20kA,手动双柱立开式,不接地，高强瓷绝缘子', ERPUnit='组', num='3', TechnicalProtocol='9906-500002150-00006', Voltage='10kV'}]
                                //[MoudleMaterials{MaterialsProjectID='2294', MaterialCodeERP='null', MaterialName='故障指示器', Spec='null', ERPUnit='只', num='3', TechnicalProtocol='null', Voltage='10kV'}, MoudleMaterials{MaterialsProjectID='2295', MaterialCodeERP='null', MaterialName='太阳能电池板', Spec='null', ERPUnit='套', num='1', TechnicalProtocol='null', Voltage='10kV'}, MoudleMaterials{MaterialsProjectID='2296', MaterialCodeERP='null', MaterialName='柱上配电自动化终端', Spec='null', ERPUnit='套', num='1', TechnicalProtocol='null', Voltage='10kV'}, MoudleMaterials{MaterialsProjectID='2297', MaterialCodeERP='null', MaterialName='布电线', Spec='BV,铜,35', ERPUnit='米', num='12', TechnicalProtocol='null', Voltage='10kV'}, MoudleMaterials{MaterialsProjectID='2298', MaterialCodeERP='500007913', MaterialName='跌落式熔断器', Spec='根据设计需要选型', ERPUnit='只', num='1', TechnicalProtocol='9906-500008441-00002', Voltage='10kV'}]
                                for (int i = 0; i < moduleMaterials.size(); i++) {
                                    serializer.startTag(null, "PointMaterial");
                                    serializer.attribute(null, "MaterialCodeERP", moduleMaterials.get(i).getMaterialCodeERP() != null ? moduleMaterials.get(i).getMaterialCodeERP() : "");//物料ERP编码
                                    serializer.attribute(null, "TechnicalProtocol", moduleMaterials.get(i).getTechnicalProtocol() != null ? moduleMaterials.get(i).getTechnicalProtocol() : "");//技术规范
                                    serializer.attribute(null, "ERPUnit", moduleMaterials.get(i).getERPUnit() == null ? "" : moduleMaterials.get(i).getERPUnit());//ERP单位
                                    serializer.attribute(null, "Voltage", moduleMaterials.get(i).getVoltage() + "");//电压等级
                                    serializer.attribute(null, "spec", moduleMaterials.get(i).getSpec() == null ? "" : moduleMaterials.get(i).getSpec());//型号
                                    serializer.attribute(null, "materialNum", moduleMaterials.get(i).getNum() == null ? "" : moduleMaterials.get(i).getNum());//物料数量
                                    serializer.attribute(null, "materialName", moduleMaterials.get(i).getMaterialName() == null ? "" : moduleMaterials.get(i).getMaterialName());//物料名称
                                    serializer.attribute(null, "materialid", moduleMaterials.get(i).getMaterialsProjectID() == null ? "" : moduleMaterials.get(i).getMaterialsProjectID());//物料id
                                    serializer.endTag(null, "PointMaterial");
                                    changeLine(serializer, enter);
                                }
                            }
                        }
                        //物料结束节点
                        serializer.endTag(null, "PointMaterials");
                        changeLine(serializer, enter);


                        serializer.endTag(null, "ColumnModel");
                        changeLine(serializer, enter);
                    }

                    List<Equipment> equipmentList1 = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(Point.getId()), EquipmentDao.Properties.Qubie.eq(0)).build().list();
                    //获取modlePropoty表里面的modleid
                    changeLine(serializer, enter);
                    for (Equipment equipment : equipmentList1) {
                        serializer.startTag(null, "PointModel");
                        /*serializer.attribute(null, "Voltagerating", getEquipId(equipment.getThreeId() + "", "Voltagerating") + "");
                        serializer.attribute(null, "SYSJ", getEquipId(equipment.getThreeId() + "", "SYSJ") + "");*///Three_id就是modleID
                        serializer.attribute(null, "Amount", equipment.getAmount() + "");
                        serializer.attribute(null, "Module_ID", equipment.getThreeId() + "");
                        serializer.attribute(null, "Module_Name", equipment.getThreeName() + "");
                        serializer.attribute(null, "ModuleXH_ID", equipment.getThreeId() + "");
                        serializer.attribute(null, "ModuleXH_Name", equipment.getThreeName() + "");
                        serializer.attribute(null, "ModuleZL_ID", equipment.getHead_id() + "");
                        serializer.attribute(null, "ModuleZL_Name", equipment.getTwoName() + "");
                        serializer.attribute(null, "ModuleFL_ID", equipment.getLever_id() + "");
                        serializer.attribute(null, "ModuleFL_Name", equipment.getName() + "");
                        serializer.attribute(null, "Module_Code", getModleCode(equipment.getThreeId() + "") + "");
                        serializer.attribute(null, "PID", equipment.getId() + "");
                        serializer.attribute(null, "Gangao", equipment.getFourId() + "");
                        serializer.attribute(null, "Shaojing", equipment.getFourName() + "");
                        changeLine(serializer, enter);
                        //serializer.attribute(null, "Index", equipment.getId() + "");

                        //物料开始节点
                        serializer.startTag(null, "PointMaterials");
                        //获取点的物料信息
                        try {
                            if (equipment.getThreeId() != null) {
                                List<ModuleMaterials> moduleMaterials = getModuleMaterials(equipment.getThreeId(), null);
                                if (moduleMaterials != null && moduleMaterials.size() > 0) {
                                    for (int i = 0; i < moduleMaterials.size(); i++) {
                                        serializer.startTag(null, "PointMaterial");
                                        serializer.attribute(null, "MaterialCodeERP", moduleMaterials.get(i).getMaterialCodeERP() != null ? moduleMaterials.get(i).getMaterialCodeERP() : "");//物料ERP编码
                                        serializer.attribute(null, "TechnicalProtocol", moduleMaterials.get(i).getTechnicalProtocol() != null ? moduleMaterials.get(i).getTechnicalProtocol() : "");//技术规范
                                        serializer.attribute(null, "ERPUnit", moduleMaterials.get(i).getERPUnit() == null ? "" : moduleMaterials.get(i).getERPUnit());//ERP单位
                                        serializer.attribute(null, "Voltage", moduleMaterials.get(i).getVoltage() == null ? "" : moduleMaterials.get(i).getVoltage());//电压等级
                                        serializer.attribute(null, "spec", moduleMaterials.get(i).getSpec() == null ? "" : moduleMaterials.get(i).getSpec());//型号
                                        serializer.attribute(null, "materialNum", moduleMaterials.get(i).getNum() == null ? "" : moduleMaterials.get(i).getNum());//物料数量
                                        serializer.attribute(null, "materialName", moduleMaterials.get(i).getMaterialName() == null ? "" : moduleMaterials.get(i).getMaterialName());//物料名称
                                        serializer.attribute(null, "materialid", moduleMaterials.get(i).getMaterialsProjectID() == null ? "" : moduleMaterials.get(i).getMaterialsProjectID());//物料id
                                        serializer.endTag(null, "PointMaterial");
                                        changeLine(serializer, enter);
                                    }
                                }

                            }
                        } catch (Error error) {
                            Log.e("errroo--==", error.toString());
                        }
                        //物料结束节点
                        serializer.endTag(null, "PointMaterials");
                        changeLine(serializer, enter);
                        serializer.endTag(null, "PointModel");
                        changeLine(serializer, enter);
                    }
                    List<Photos> photosList = App.getInstances().getDaoSession().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(Point.getId())).build().list();
                    for (Photos photos : photosList) {
                        serializer.startTag(null, "Multimedia");
                        //serializer.attribute(null, "Multimedia_Name", photos.getName() + "");
                        serializer.attribute(null, "Multimedia_Path", photos.getName() + "");
                        serializer.attribute(null, "PID", photos.getId() + "");
                        //serializer.attribute(null, "Index", photos.getId() + "");
                        serializer.endTag(null, "Multimedia");
                        changeLine(serializer, enter);
                    }
                    serializer.endTag(null, "Point");
                    changeLine(serializer, enter);
                }


                //地型点
                if (czzts.size() > 0) {
                    for (Point Point : czzts) {
                        serializer.startTag(null, "TopographicPoint");
                        serializer.attribute(null, "uid", Point.getUid() + "");
                        serializer.attribute(null, "center_lat", Point.getLatitude() + "");
                        serializer.attribute(null, "center_lng", Point.getLongitude() + "");
                        serializer.attribute(null, "name", Point.getGlsb() + "");//强哥要的地形点的code
                        if (Point.getLegendTypeKey() != null) {
                            Log.e("pintLegendTypeKey", Point.getLegendTypeKey().replace("&#13;", "") + "");
                            serializer.attribute(null, "LegendTypeKey", Point.getLegendTypeKey().trim().replace("&#13;", "").replace("\n", "") + "");

                        }
                        serializer.attribute(null, "address", Point.getAddress() + "");
                        serializer.attribute(null, "t_length", Point.getLength() + "");
                        serializer.attribute(null, "t_width", Point.getWidth() + "");
                        serializer.attribute(null, "t_hight", Point.getHigh() + "");
                        serializer.attribute(null, "t_type", Point.getSblx() + "");
                        serializer.attribute(null, "equipId", Point.getEquipType_id() + "");
                        serializer.attribute(null, "flag", Point.getMark() + "");
                        serializer.attribute(null, "mark", Point.getMark() + "");
                        serializer.attribute(null, "remark", Point.getNote() + "");
                        serializer.attribute(null, "t_lat", Point.getLatitude() + "");
                        serializer.attribute(null, "t_lng", Point.getLongitude() + "");
                        serializer.attribute(null, "rotate_lat", Point.getLatitude() + "");
                        serializer.attribute(null, "rotate_lng", Point.getLongitude() + "");
                        //serializer.attribute(null, "Index", Point.getId() + "");
                        changeLine(serializer, enter);
                        serializer.endTag(null, "TopographicPoint");
                    }
                }


                final List<Line> lineList = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.ProjectId.eq(id)).build().list();
                if (lineList.size() > 0) {
                    for (Line line : lineList) {
                        serializer.startTag(null, "Line");

                        if (line.getParallelPole() != null) {
                            serializer.attribute(null, "LineVersionName", line.getParallelPole() + "");
                        }

                        if (line.getMethodName() != null) {
                            serializer.attribute(null, "LineMethodName", line.getMethodName() + "");
                        }
                        if (line.getPath() != null) {
                            serializer.attribute(null, "LineFS_Method", line.getPath() + "");
                        }
                        if (line.getLegendTypeKey() != null) {
                            Log.e("LineLegendTypeKey", line.getLegendTypeKey().replace("&#13;", ""));
                            serializer.attribute(null, "LegendTypeKey", line.getLegendTypeKey().trim().replace("&#13;", "").replace("\n", "") + "");
                        }
                        serializer.attribute(null, "Start_equip", line.getStart_id() + "");
                        serializer.attribute(null, "End_equip", line.getEnd_id() + "");
                        serializer.attribute(null, "Line_code", line.getName() + "");
                        serializer.attribute(null, "LineLen", line.getLength() + "");
                        serializer.attribute(null, "LineType", line.getType() + "");
                        serializer.attribute(null, "Module_ID", line.getModuleID() + "");
                        serializer.attribute(null, "Module_Name", line.getModuleTxt() + "");
                        serializer.attribute(null, "LineStatue", line.getState() + "");
                        serializer.attribute(null, "LineBackNum", line.getBackNum() + "");
                        serializer.attribute(null, "LineNum", line.getNum() + "");
                        serializer.attribute(null, "LineTypeID", line.getTypeId() == null ? "" : line.getTypeId());
                        serializer.attribute(null, "LineLonB", line.getLonB() == null ? "" : line.getLonB());
                        serializer.attribute(null, "LineLatB", line.getLatB() + "");
                        serializer.attribute(null, "LineLonA", line.getLonA() + "");
                        serializer.attribute(null, "LineLatA", line.getLatA() == null ? "" : line.getLatA());
                        serializer.attribute(null, "LineName", line.getName() == null ? "" : line.getName());
                        if (line.getCid() != null && !line.getCid().isEmpty()) {
                            if (line.getCid().length() > 12) {
                                serializer.attribute(null, "LineId", line.getCid() + "");
                            } else {
                                serializer.attribute(null, "LineId", getUUID() + "");

                            }
                        } else {
                            serializer.attribute(null, "LineId", line.getId() + "");

                        }
                        //isT=1（是）其他 ""  线 isT （是）那就是T分支路线="1", 十字街="2" 主线路  ""  "同杆塔并架"
                        //同杆并架 parallelPole=1 表示 isT="1" 是T分阶 ： 其他的 parallelPole=0或者其他的 isT=""   is那就是T分支路线="1", 十字街="2" 主线路  ""  "同杆塔并架"
                        if (line.getParallelPole() != null && (line.getParallelPole().equals("1") || line.getParallelPole().equals("2"))) {
                            serializer.attribute(null, "isT", line.getParallelPole());
                        } else {
                            if (line.getParallelPole() != null) {
                                serializer.attribute(null, "isT", "0");
                            }
                        }
                        //物料开始节点
                        serializer.startTag(null, "LineMaterials");
                        //获取点的物料信息
                        List<ModuleMaterials> moduleMaterials = getModuleMaterials(line.getModuleID(), line);
                        if (moduleMaterials != null && moduleMaterials.size() > 0) {
                            //Log.e("TAG", "getXmlFile线: " + moduleMaterials.toString());
                            for (int i = 0; i < moduleMaterials.size(); i++) {
                                serializer.startTag(null, "LineMaterial");
                                serializer.attribute(null, "MaterialCodeERP", moduleMaterials.get(i).getMaterialCodeERP() != null ? moduleMaterials.get(i).getMaterialCodeERP() : "");//物料ERP编码
                                serializer.attribute(null, "TechnicalProtocol", moduleMaterials.get(i).getTechnicalProtocol() != null ? moduleMaterials.get(i).getTechnicalProtocol() : "");//技术规范
                                serializer.attribute(null, "ERPUnit", moduleMaterials.get(i).getERPUnit() == null ? "" : moduleMaterials.get(i).getERPUnit());//ERP单位
                                serializer.attribute(null, "Voltage", moduleMaterials.get(i).getVoltage() == null ? "" : moduleMaterials.get(i).getVoltage());//电压等级
                                serializer.attribute(null, "spec", moduleMaterials.get(i).getSpec() == null ? "" : moduleMaterials.get(i).getSpec());//型号
                                serializer.attribute(null, "materialNum", moduleMaterials.get(i).getNum() == null ? "" : moduleMaterials.get(i).getNum());//物料数量
                                serializer.attribute(null, "materialName", moduleMaterials.get(i).getMaterialName() == null ? "" : moduleMaterials.get(i).getMaterialName());//物料名称
                                serializer.attribute(null, "materialid", moduleMaterials.get(i).getMaterialsProjectID() == null ? "" : moduleMaterials.get(i).getMaterialsProjectID());//物料id
                                serializer.endTag(null, "LineMaterial");
                                changeLine(serializer, enter);
                            }
                        }
                        //物料结束节点
                        serializer.endTag(null, "LineMaterials");
                        changeLine(serializer, enter);

                        //serializer.attribute(null, "Index", line.getId() + "");
                            /*List<Equipment> equipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.Point_id.eq(line.getId()), EquipmentDao.Properties.Qubie.eq(1)).build().list();
                            for (Equipment equipment : equipmentList) {
                                changeLine(serializer, enter);
                                serializer.startTag(null, "ColumnModel");
                                serializer.attribute(null, "Amount", equipment.getAmount() + "");
                                serializer.attribute(null, "Module_ID", equipment.getThreeId() + "");
                                serializer.attribute(null, "Module_Name", equipment.getThreeName() + "");
                                serializer.attribute(null, "ModuleXH_ID", equipment.getThreeId() + "");
                                serializer.attribute(null, "ModuleXH_Name", equipment.getThreeName() + "");
                                serializer.attribute(null, "ModuleZL_ID", equipment.getHead_id() + "");
                                serializer.attribute(null, "ModuleZL_Name", equipment.getTwo_name() + "");
                                serializer.attribute(null, "ModuleFL_ID", equipment.getLever_id() + "");
                                serializer.attribute(null, "ModuleFL_Name", equipment.getName() + "");
                                serializer.attribute(null, "Module_Code", getModleCode(equipment.getThreeId() + "") + "");
                                serializer.attribute(null, "PID", equipment.getId() + "");
                                serializer.endTag(null, "ColumnModel");
                            }*/


                        changeLine(serializer, enter);
                        serializer.endTag(null, "Line");
                    }
                }

                try {
                    serializer.endTag(null, "Projects");
                    changeLine(serializer, enter);
                    serializer.endDocument();
                    serializer.flush();
                    fileos.close();
                } catch (IOException | IllegalArgumentException | IllegalStateException e) {
                    Log.e("erros=", e.getMessage());
                    e.printStackTrace();
                }

                //MyUtils.getToast(context, "上传成功");

            } else {
                ToastUtils.showShort("没有点数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("erros=", e.getMessage());

        }

        return xmlFile;
    }

    private File getAddItemXmlFile() {
        int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        int permission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    (Activity) context,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        String enter = System.getProperty("line.separator");//换行
        //这里是保存文件夹。
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhneprojectinfo/" + name + "/" + name);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        File xmlFile = null;
        Project item = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().unique();
        xmlFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhneprojectinfo/" + name + "/" + name, name + item.getId() + ".xml");
        xmlFile.setWritable(true);
        FileOutputStream fileos = null;
        try {
            fileos = new FileOutputStream(xmlFile);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fileos, "UTF-8");
            serializer.startDocument(null, true);
            changeLine(serializer, enter);
            //Unit: ,|,, |,,直埋
            //50000,50000|,, |,,直埋                   选择了杆塔的 类别和杆形
            //Unit: 50000,50001|11,346, |13,483,直埋
            //Unit: ,|,, |13,483,直埋                  电缆路线
            //Unit: ,|11,346, |,,直埋                  架空线路
            //
            /*<Projects>
            <ProjectId>f3674ae7-7666-487d-bae7-8acaf0fa6550</ProjectId>
            <ProjectName>项目名称</ProjectName>
            <ProjectTime>创建时间</ ProjectTime >
            <ModuleTypeId>选型杆塔的类别ID  ModuleTypeID</ ModuleTypeId >
            <ModuleId>杆型ID[非预应力,整根杆，12m,190mm，N]</ModuleId>
            <OverheadEquipId>架空类别Id</OverheadEquipId>
            <OverheadModuleId>架空线路ID</OverheadModuleId>
            <CableEquipId>电缆类别Id</CableEquipId>
            <CableModuleId>电缆线路ID</CableModuleId>
            <CableLayingWay>敷设方式</CableLayingWay>
            <Voltage>10kV</Voltage>
            <State>新建</State>
            <Note>项目备注</Note>
            </Projects>*/
            serializer.startTag(null, "Projects");
            /**项目ID*/
            changeLine(serializer, enter);
            serializer.startTag(null, "ProjectId");
            serializer.text(item.getProjectId() + "");
            serializer.endTag(null, "ProjectId");
            changeLine(serializer, enter);
            /**项目名称**/
            serializer.startTag(null, "ProjectName");
            serializer.text(item.getName() + "");
            serializer.endTag(null, "ProjectName");
            changeLine(serializer, enter);

            //时间
            serializer.startTag(null, "ProjectTime");
            serializer.text(item.getTime() + "");
            serializer.endTag(null, "ProjectTime");
            changeLine(serializer, enter);




            /*
            *
            *    if(items.getGanxinModuleTypeId()!=null){//类别 ModuleTypeID
                ganxinLiebieStringID=items.getGanxinModuleTypeId();
            }
            if(items.getGanxinModuleId()!=null){//杆型ID[非预应力,整根杆，12m,190mm，N]
                ganxinLiebieTvID=items.getGanxinModuleTypeId();
                xuanxingCenterTv.setText(getGangaoResultId(ganxinLiebieTvID));
            }
            if(items.getJiakongEquipId()!=null){//杆型ID[非预应力,整根杆，12m,190mm，N]
                jiakongStringID = items.getJiakongEquipId();
                jiakongStringTvID = items.getJiakongModuleId();
                jiakongTv.setText(getLuxianXuanxingName(items.getJiakongModuleId()));

            }
            if(items.getDilanEquipId()!=null){//杆型ID[非预应力,整根杆，12m,190mm，N]
                dianlanStringID = items.getDilanEquipId();
                dianlanStringTvID = items.getDilanModuleId();
                dianlanTv.setText(getLuxianXuanxingName(dianlanStringTvID));

            }
            *
            * */
            //选型ID
            serializer.startTag(null, "ModuleTypeId");
            serializer.text(item.getGanxinModuleTypeId());
            serializer.endTag(null, "ModuleTypeId");
            changeLine(serializer, enter);

            //杆型类别ID
            serializer.startTag(null, "ModuleId");
            serializer.text(item.getGanxinModuleId());
            serializer.endTag(null, "ModuleId");
            changeLine(serializer, enter);


            //架空类别Id
            serializer.startTag(null, "OverheadEquipId");
            serializer.text(item.getJiakongEquipId());
            serializer.endTag(null, "OverheadEquipId");
            changeLine(serializer, enter);

            //架空线路ID
            serializer.startTag(null, "OverheadModuleId");
            serializer.text(item.getJiakongModuleId());
            serializer.endTag(null, "OverheadModuleId");
            changeLine(serializer, enter);


            //电缆类别Id
            serializer.startTag(null, "CableEquipId");
            serializer.text(item.getDilanEquipId());
            serializer.endTag(null, "CableEquipId");
            changeLine(serializer, enter);

            //电缆线路ID
            serializer.startTag(null, "CableModuleId");
            serializer.text(item.getDilanModuleId());
            serializer.endTag(null, "CableModuleId");
            changeLine(serializer, enter);

            //敷设方式
            serializer.startTag(null, "CableLayingWay");
            serializer.text(item.getPath());
            serializer.endTag(null, "CableLayingWay");
            changeLine(serializer, enter);

            //电压等级
            serializer.startTag(null, "Voltage");
            serializer.text(item.getVoltage() + "");
            serializer.endTag(null, "Voltage");
            changeLine(serializer, enter);

            //状态建设类型[原有，改造，新建]
            serializer.startTag(null, "State");
            serializer.text(item.getType() + "");
            serializer.endTag(null, "State");
            changeLine(serializer, enter);

            //备注
            serializer.startTag(null, "Note");
            serializer.text(item.getNote() + "");
            serializer.endTag(null, "Note");
            changeLine(serializer, enter);

            serializer.endTag(null, "Projects");
            changeLine(serializer, enter);
            serializer.endDocument();
            serializer.flush();
            fileos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return xmlFile;
    }

    private File getTrajectoryXmlFile(Trajectory trajectory) {
        int REQUEST_EXTERNAL_STORAGE = 1;
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
        int permission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    (Activity) context,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        String enter = System.getProperty("line.separator");//换行
        //这里是保存文件夹。
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/trajectory/" + name + "/" + name);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        //Log.e("stringAniToSting2", trajectory.toString());
        File xmlFile = null;
        Project item = App.getInstances().getDaoSession().getProjectDao().queryBuilder().where(ProjectDao.Properties.Id.eq(id)).build().unique();
        xmlFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/trajectory/" + name + "/" + name, name + item.getId() + ".xml");
        xmlFile.setWritable(true);
        FileOutputStream fileos = null;
        /* <?xml version="1.0" encoding="UTF-8" standalone="true"?>
            <Trajectory>
            <ProjectId>f3674ae7-7666-487d-bae7-8acaf0fa6550</ProjectId>
            <Longitude>117.234678</Longitude>
            <Latitude>39.131106</Latitude>
            <Time>1575876821</Time>
            </Trajectory>
        *
        *
        * */
        try {
            fileos = new FileOutputStream(xmlFile);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fileos, "UTF-8");
            serializer.startDocument(null, true);
            changeLine(serializer, enter);

            serializer.startTag(null, "Trajectory");
            /**项目ID*/
            changeLine(serializer, enter);

            serializer.startTag(null, "ProjectId");
            serializer.text(trajectory.getProjectId() == null ? getUUID() : trajectory.getProjectId());
            serializer.endTag(null, "ProjectId");
            changeLine(serializer, enter);

            serializer.startTag(null, "Longitude");
            serializer.text(trajectory.getLongitude() + "");
            serializer.endTag(null, "Longitude");
            changeLine(serializer, enter);

            serializer.startTag(null, "Latitude");
            serializer.text(trajectory.getLatitude() + "");
            serializer.endTag(null, "Latitude");
            changeLine(serializer, enter);

            serializer.startTag(null, "Address");
            serializer.text(trajectory.getAddress() + "");
            serializer.endTag(null, "Address");
            changeLine(serializer, enter);

            serializer.startTag(null, "Time");
            serializer.text(trajectory.getTime() + "");
            serializer.endTag(null, "Time");
            changeLine(serializer, enter);

            serializer.endTag(null, "Trajectory");
            changeLine(serializer, enter);
            serializer.endDocument();
            serializer.flush();
            fileos.close();

        } catch (Exception ignored) {

        }
        return xmlFile;
    }

    private String getDefaultLineType(String lineName) {
        String defualtLineType = "1";
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert (db != null);
        @SuppressLint("Recycle")
        Cursor cursor = db.rawQuery("select * from EquipType m where m.name =" + "'" + lineName + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            defualtLineType = cursor.getString(4);
        }

        cursor.close();

        return defualtLineType;
    }

    /**
     * 获取物料
     *
     * @param moduleID id
     * @param line     线
     * @return 物料集合
     */
    private List<ModuleMaterials> getModuleMaterials(String moduleID, Line line) {
        List<ModuleMaterials> moduleMaterialsList = new ArrayList<>();
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        //Log.e("这样的你", "select vmp.* from View_ModuleMaterials_ProjectMaterials vmp where vmp.ModuleID = " + "'" + moduleID + "'");
        Cursor cursor = db.rawQuery("select vmp.* from View_ModuleMaterials_ProjectMaterials vmp where vmp.ModuleID = " + "'" + moduleID + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            ModuleMaterials moduleMaterials = new ModuleMaterials();
            moduleMaterials.setMaterialsProjectID(cursor.getString(4));
            moduleMaterials.setMaterialCodeERP(cursor.getString(6));
            moduleMaterials.setMaterialName(cursor.getString(5));
            moduleMaterials.setSpec(cursor.getString(7));
            String erpUnit = cursor.getString(12);
            moduleMaterials.setERPUnit(erpUnit);
            if (line != null) {
                String num = cursor.getString(2);
                //如果是千米或米，保留小数，如果不是，四舍五入取整。
                if (erpUnit.equals("千米") || erpUnit.equals("米")) {
                    moduleMaterials.setNum(Double.parseDouble(getNumber(num, Double.parseDouble(line.getLength()) / 1000 + "", "1", line.getBackNum(), line.getNum())) + "");
                } else {
                    moduleMaterials.setNum(Math.round(Double.parseDouble(getNumber(num, Double.parseDouble(line.getLength()) / 1000 + "", "1", line.getBackNum(), line.getNum()))) + "");
                }
            } else {
                moduleMaterials.setNum(cursor.getString(2));
            }
            moduleMaterials.setTechnicalProtocol(cursor.getString(15));
            moduleMaterials.setVoltage(cursor.getString(8));
            moduleMaterialsList.add(moduleMaterials);
        }
        cursor.close();

        return moduleMaterialsList;
    }

    private String getIconBySblx(String value, Context context) {
        String nameIcon = "";
        SQLiteDatabase db = SQLiteDatabaseUtils.getInstance().getSQLiteDatabase();
        assert (db != null);
        @SuppressLint("Recycle")
        Cursor cursor = db.rawQuery("select * from EquipType m where m.name =" + "'" + value + "'", null);//此处的db是表名，name是列名
        while (cursor.moveToNext()) {
            nameIcon = cursor.getString(5);

        }

        cursor.close();

        return nameIcon;
    }

    /**
     * 获取数据
     *
     * @param NUMBER 数量
     * @param LENGTH 长度
     * @param AMOUNT 数
     * @param H      回路
     * @param G      根数
     * @return num
     */
    private String getNumber(String NUMBER, String LENGTH, String AMOUNT, String H, String G) {
        String replaceResult = (NUMBER + "*" + AMOUNT).replace("L", LENGTH).replace("H", H).replace("G", G);
        Log.e("replaceGS=", replaceResult);
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(3);
        //Log.e("reslsfjl=", eval(replaceResult) + "");
        return (double) Math.round(eval(replaceResult) * 1000) / 1000 + "";
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     *
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {//如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 获取UUID
     *
     * @return uuid
     */
    private String getUUID() {
        return UUID.randomUUID() + "";
    }

    /**
     * 经纬度转墨卡托
     *
     * @param LonLat 经纬度坐标
     * @return
     */
    public static LocationPoint lonLatToMercator(LocationPoint LonLat) {
        LocationPoint mercator = new LocationPoint();
        double x = (LonLat.getX() * 20037508.342789 / 180);
        double y = (Math.log(Math.tan((90 + LonLat.getY()) * Math.PI / 360)) / (Math.PI / 180));
        y = (double) (y * 20037508.342789 / 180);
        mercator.setX(x);

        return mercator;
    }

    /**
     * https://blog.csdn.net/hnyzwtf/article/details/51453693
     * 写kml文件
     *
     * @param strs
     * @param kmlName
     * @throws IOException
     */
    public static void writeKml(String[] strs, String kmlName) throws IOException {
        String[] files = strs;
        //File kmlFile = new File("person.kml");
        OutputStream os = new BufferedOutputStream(new FileOutputStream(kmlName + ".kml"));
        ZipOutputStream zos = new ZipOutputStream(os);
        byte[] buf = new byte[8192];
        int len;
        for (int i = 0; i < files.length; i++) {
            File file = new File(files[i]);
            if (!file.isFile())
                continue;
            ZipEntry ze = new ZipEntry(file.getName());
            zos.putNextEntry(ze);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            while ((len = bis.read(buf)) > 0) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
        }

        zos.closeEntry();
        zos.close();

    }

    private GaussKrugerProjection.Tuple get2000XY(String lat, String lng) {
        CoordinateTool.Location location = CoordinateTool.dbToWGS84(Double.parseDouble(lat), Double.parseDouble(lng));//转换获取GPS84坐标
        GaussKrugerProjection.Tuple tuple = GaussKrugerProjection.GetXY(location.getLat(), location.getLng(), 3, false);//获取大地2000的X,Y
        return tuple;
    }

    public static void main(String[] args) {
        // （40544018，3479513）转成经纬度得到（364.359166， 145.9186111）
    }
}
